﻿using System;
using System.Reflection;
using System.Collections.Generic;
using Dynamic.Core.Reflection;

namespace Dynamic.Core.Utility
{
    /// <summary>
    /// 反射通用类
    /// </summary>
    public static class RefectionUtility
    {
        /// <summary>
        /// 得到属性信息
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static PropertyInfo GetPropertyInfo(object obj,string name)
        { PropertyInfo pi = obj.GetType().GetProperty(name);
            if ( pi == null )
            {
                foreach ( PropertyInfo item in obj.GetType().GetProperties() )
                {
                    if ( string.Compare(item.Name, name,true)==0 )
                    {
                        pi = item;
                        break;
                    }
                }
            }

            return pi;
        }

        /// <summary>
        /// 得到实例的某一属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static object GetPropertyValue(object obj,string name)
        {
            PropertyInfo pi = GetPropertyInfo(obj, name);

            return pi.FastGetValue(obj);
        }

        /// <summary>
        /// 得到实例的所有属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Dictionary<string,object> GetPropertyValues(object obj)
        {
            Dictionary<string, object> reval = new Dictionary<string, object>();

            foreach (PropertyInfo pi in obj.GetType().GetProperties())
            {
                reval.Add(pi.Name, pi.FastGetValue(obj));
            }

            return reval;
        }

        /// <summary>
        /// 设置某一属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetPropertyValue(object obj, string name, object value)
        {
            PropertyInfo pi = GetPropertyInfo(obj, name);
            pi.FastSetValue(obj, value);
        }

        /// <summary>
        /// 设置部分属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetPropertyValues(object obj, Dictionary<string, object> keyValues)
        {
            foreach (KeyValuePair<string, object> keyValue in keyValues)
            {
                SetPropertyValue(obj, keyValue.Key, keyValue.Value);
            }
        }
    }
}
